package Pet.Management.controller;

import Pet.Management.domain.entity.TaskNode;
import Pet.Management.service.TaskNodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * 任务节点图片控制器
 */
@RestController
@RequestMapping("/api/pet-care/task-nodes")
public class TaskNodeImageController {

    private static final Logger logger = LoggerFactory.getLogger(TaskNodeImageController.class);

    @Autowired
    private TaskNodeService taskNodeService;

    /**
     * 获取任务节点图片
     */
    @GetMapping(value = "/{nodeId}/image")
    public ResponseEntity<byte[]> getTaskNodeImage(@PathVariable Long nodeId) {
        logger.info("TaskNodeImageController: Fetching image for task node: {}", nodeId);
        
        try {
            Optional<TaskNode> taskNodeOpt = taskNodeService.getTaskNodeById(nodeId);
            if (!taskNodeOpt.isPresent()) {
                logger.warn("TaskNodeImageController: Task node not found: {}", nodeId);
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
            
            TaskNode taskNode = taskNodeOpt.get();
            byte[] imageData = taskNode.getProofImage();
            
            logger.info("TaskNodeImageController: Task node found, image data null? {}", (imageData == null));
            
            if (imageData == null || imageData.length == 0) {
                logger.warn("TaskNodeImageController: No image data for task node: {}", nodeId);
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            
            // Add cache control to prevent browser caching
            headers.setCacheControl("no-cache, no-store, must-revalidate");
            headers.setPragma("no-cache");
            headers.setExpires(0);
            
            logger.info("TaskNodeImageController: Successfully returning image data for task node {}, size: {} bytes", 
                    nodeId, imageData.length);
            
            return new ResponseEntity<>(imageData, headers, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("TaskNodeImageController: Error fetching image for task node: {}", nodeId, e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
} 